import { Component, OnInit, ViewChild } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router, ActivatedRoute } from '@angular/router';
import { NzModalService } from 'ng-zorro-antd/modal';
import { NzCascaderOption } from 'ng-zorro-antd/cascader';

import { CommonService } from '../../../services-common/common.service';
import { defalutImg } from '../../../comm';
import { LoveOrderManageService } from '../love-order-manage.service';
import { PermissionService } from '../../../service/permission.service';

@Component({
  selector: 'app-love-order-details',
  templateUrl: './love-order-details.component.html',
  styleUrls: ['./love-order-details.component.scss']
})
export class LoveOrderDetailsComponent implements OnInit {
  @ViewChild('detailRef') detailRef: any; // 评估详情
  @ViewChild('userInfoRef') userInfoRef: any;
  @ViewChild('reportModalRef') reportModalRef: any;

  routerParams: any = {};
  cardSize: any = 'default';
  fallback: string = defalutImg;
  batchDefaultImg: string = '../../../../assets/images/batch-default.png';

  // 订单来源
  orderSourceOptions: any = [];
  // 订单详情
  orderDetailsData: any = {};
  // 机型估价详情
  orderRecycleModel: any = {};
  // 订单动态
  orderDynamic: any = [];
  // 跟进信息
  followTableData: any = [];
  // 机器验机详情list
  machineDetailsTable: any = [];

  // 评估情况list ueval
  situationLists: any = [];

  /****************************** Modal **********************************/
  // 物流详情
  isLogisticsVisible: boolean = false;
  logisticsLists: any = [];

  // 收款
  isCollectionVisible: boolean = false;
  collectionForm!: FormGroup;

  // 打款
  isPaymentVisible: boolean = false;
  paymentForm!: FormGroup;
  // 打款失败原因 1-未添加收款信息 2-收款信息有误
  paymentReasons: any = [
    { value: '1', label: '用户未添加收款信息' },
    { value: '2', label: '收款信息错误' }
  ];

  // 不卖了退款
  isReturnGoodsVisible: boolean = false;
  returnGoodsForm!: FormGroup;
  returnSubLoading: boolean = false;
  adressText: string = '';
  nzOptions: Array<{ value: Number, label: string, children: [] }> = [];
  addressArea: any;
  /** load data async execute by `nzLoadData` method */
  loadTreeData = (node: NzCascaderOption, index: number) => {
    return new Promise((resolve: any) => {
      if (index < 0) {
        node.children = this.addressArea.province;
      } else if (index === 0) {
        // @ts-ignore
        node.children = this.addressArea.city[node.value];
      } else {
        // @ts-ignore
        node.children = this.addressArea.county[node.value];
        // node.children = scenicspots[node.value];
      }
      resolve();
    });
  };

  // 地址选择文本
  onChanges(values: number[]): void {
    let provinceStr = values.length ? this.addressFilter(this.addressArea.province, values[0]) : '';
    let cityStr = values.length ? this.addressFilter(this.addressArea.city, values[1]) : '';
    let areaStr = values.length ? this.addressFilter(this.addressArea.county, values[2]) : '';
    this.adressText = provinceStr + cityStr + areaStr;
  }
  // 地址文本filter
  addressFilter(arrys: any, contrastId: number) {
    let str = '';
    if (Array.isArray(arrys)) {
      let tmpObj = arrys.find(tag => tag.value == contrastId);
      str = tmpObj.label;
    } else {
      for (let key in arrys) {
        arrys[key].forEach((ele: any) => {
          if (ele.value == contrastId) {
            str = ele.label;
          }
        });
      }
    }
    return str;
  }

  // 立即收钱
  isMachineVisible: boolean = false;
  machineForm!: FormGroup;
  machineType: number = 0; // 0：不卖了，1：收钱

  // 添加跟进
  isFollowVisible: boolean = false;
  followForm!: FormGroup;

  /**
   * 验机详情--添加信息
   * ----------------------------------------------------------------
   */
  isReasonVisible: boolean = false;
  reasonForm!: FormGroup;
  reasonItem: any = {};

  /**
   * 查看评估详情 Modal
   * ----------------------------------------------------------------
   */
  previewParams = {
    moduleId: '', // 机型ID
    evalList: [], // 对比项
    umname: '', // 机型名称
    totalNum: 0 // 预估合计
  }

  /**
   * 添加退货信息 Modal
   * ----------------------------------------------------------------
   */
  isReturnInfoVisible: boolean = false;
  returnInfosForm!: FormGroup;

  /**
   * 取消订单 Modal
   * ----------------------------------------------------------------
   */
  isCancelVisible: boolean = false;
  cancelOrderForm!: FormGroup;

  /**
   * 继续回收 Modal
   * ----------------------------------------------------------------
   */
  isContinueVisible: boolean = false;
  continueOrderForm!: FormGroup;

  /**
   * 反悔退货 Modal
   * ----------------------------------------------------------------
   */
  isRegretVisible: boolean = false;
  regretOrderForm!: FormGroup;

  // 验机报告 Modal
  reportRequestData: any = {};

  // 加价设置 Modal
  makeupVisible = false;

  /**
   * 关闭订单
   * ----------------------------------------------------------------
   */
  closeOrderVisisble = false;
  closeOrderLoading = false;
  closeOrderRemark = '';

  // 商品信息
  goodsInfos: any = {};
  goodsTableData: any = [];

  /**
   * 发送短信 Modal
   * ----------------------------------------------------------------
   */
  isSendMsgVisible: boolean = false;
  sendMsgLoading: boolean = false;
  shortMsgOptions = [
    {id: 0, key: '不符合回收', value: '【爱思回收】尊敬的用户您好，您的设备经检测不符合回收条件，请尽快联系我司进行退货处理。客服热线:4007806888。'},
    {id: 1, key: '屏幕锁/账号未解除', value: '【爱思回收】尊敬的用户您好，您的设备屏幕锁/系统账号未解除，因此无法检测给出回收报价，请尽快联系我司进行处理。客服热线:4007806888。'},
    {id: 2, key: '检测结果不一致', value: '【爱思回收】尊敬的用户您好，您的设备已完成验机，请48小时内前往爱思回收或联系我司客服进行确认。客服热线:4007806888。'},
    {id: 3, key: '收款信息为空或有误', value: '【爱思回收】尊敬的用户您好，您的收款信息为空或有误导致我司无法给您打款，请尽快前往爱思回收或联系我司进行确认。客服热线:4007806888。'}
  ];
  msgTemplType = null;
  msgTemplContent: string = '';

  constructor(
    private fb: FormBuilder,
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private services: LoveOrderManageService,
    private message: NzMessageService,
    private modal: NzModalService,
    public permission: PermissionService,
    private commonService: CommonService
  ) {
    activatedRoute.queryParams.subscribe((res: any) => {
      this.routerParams = res || {};
    })
  }

  ngOnInit(): void {
    // 省市区
    import('../../../services-common/city').then(m => {
      this.addressArea = m.default;
    });
    // 收款信息
    this.collectionForm = this.fb.group({
      payacc: ['', [Validators.required]], // 账号(手机号)
      // payway: ['', [Validators.required]], // 账户类型
      payname: ['', [Validators.required]],
      remarks: ['', [Validators.required]]
    });
    // 打款失败
    this.paymentForm = this.fb.group({
      type: ['', [Validators.required]],
      remarks: ['']
    });
    // 不卖退款
    this.returnGoodsForm = this.fb.group({
      backRemarks: ['', [Validators.required]],
      backLnker: ['', [Validators.required]],
      backLnktel: ['', [Validators.required]],
      backI5addrid: [[], [Validators.required]],
      backExpdtl: ['', [Validators.required]],
      remarks: ['', [Validators.required]],
    });

    // 添加编辑退货信息
    this.returnInfosForm = this.fb.group({
      // backRemarks: ['', [Validators.required]],
      resultQuantity: ['', [Validators.required]], // 退货数量
      isFreight: ['0', [Validators.required]], // 邮费承担
      backLnker: ['', [Validators.required]],
      backLnktel: ['', [Validators.required]],
      backI5addrid: [[], [Validators.required]],
      backExpdtl: ['', [Validators.required]]
      // remarks: ['', [Validators.required]],
    });

    // 收钱
    this.machineForm = this.fb.group({
      remarks: ['', [Validators.required]]
    });
    // 添加跟进
    this.followForm = this.fb.group({
      remarks: ['', [Validators.required]]
    });

    // 验机详情--添加信息
    this.reasonForm = this.fb.group({
      remarks: ['', [Validators.required]]
    });

    // 取消订单
    this.cancelOrderForm = this.fb.group({
      note: ['', [Validators.required]]
    })

    // 继续回收
    this.continueOrderForm = this.fb.group({
      remark: ['', [Validators.required]]
    })

    // 反悔退货
    this.regretOrderForm = this.fb.group({
      resultQuantity: ['', [Validators.required]], // 退货数量
      isFreight: ['0', [Validators.required]], // 邮费承担 0我司承担 1用户承担
      backRemarks: ['', [Validators.required]], // 退货原因
      backLnker: ['', [Validators.required]], // 收货人
      backLnktel: ['', [Validators.required]], // 手机号码
      backI5addrid: ['', [Validators.required]], // 退货地址
      backExpdtl: ['', [Validators.required]], // 详细地址
      note: ['', [Validators.required]], // 备注
      backExparea: [''] // 地址拼接
    })

    this.getChannelList();
    this.loadDetailsData();
  }

  // 查询订单来源
  async getChannelList() {
    const res: any = await this.services.dictListData('channel');
    if (res.code == 0) {
      const { list } = res.data || {};
      this.orderSourceOptions = list || [];
    } else {
      this.message.error(res.message);
    }
  }

  // 详情loadData
  async loadDetailsData() {
    const msgId = this.message.loading('加载中..', { nzDuration: 0 }).messageId;
    const res: any = await this.services.getOrderDetails({id: this.routerParams.id});
    this.message.remove(msgId);
    
    if (res.code == 0) {
      const { evalList, followInfo, phoneCheckList, jo, orderInfo, recycleModel } = res.data || {};
      this.orderDynamic = orderInfo.orderDynamic ? JSON.parse(orderInfo.orderDynamic).reverse() : []; // 动态List
      // this.logisticsLists = orderInfo.dynamic ? JSON.parse(orderInfo.dynamic) : []; // 物流List
      this.orderDetailsData = orderInfo || {};
      this.machineDetailsTable = phoneCheckList || []; // 机器验机详情
      this.situationLists = orderInfo?.ueval ? JSON.parse(orderInfo?.ueval) : []; // 评估情况list
      this.followTableData = followInfo || []; // 跟进List
      this.orderRecycleModel = recycleModel || {}; // 机型估价详情

      // 评估详情
      this.previewParams.evalList = (evalList && evalList.length) ? evalList : [];
      this.previewParams.moduleId = orderInfo?.umid || '';
      this.previewParams.totalNum = (Number(orderInfo.uprc) || 0) + (Number(orderInfo.orderAprc) || 0);
      this.previewParams.umname = orderInfo.umname || '';

      // 商品信息Table  renewalSource: 1、配件 2、二手
      this.goodsInfos = jo || {};
      this.goodsTableData = jo?.orderDetails || [];
    } else {
      this.message.error(res.message);
    }
  }

  // 查看用户信息
  userInfoPreview() {
    this.userInfoRef.isVisible = true;
  }

  submitForm() {
    if (this.collectionForm.valid) {
      // this.subFormInterface();
      this.isCollectionVisible = false;
    } else {
      Object.values(this.collectionForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }

  handleCancel() {
    this.isLogisticsVisible = false;
  }

  /**
   * ----------------------------------------------------------------
   * 收款信息 Modal
   * ----------------------------------------------------------------
   */
  showCollectionModal() {
    this.collectionForm.reset();
    this.collectionForm.patchValue({
      payacc: this.orderDetailsData.payacc, // 账号(手机号)
      payway: this.orderDetailsData.payway, // 账户类型
      payname: this.orderDetailsData.payname,
      remarks: ''
    })
    this.isCollectionVisible = true;
  }
  collectionCancel() {
    this.isCollectionVisible = false;
  }
  async submitCollection() {
    if (this.collectionForm.valid) {
      let params = {
        ...this.collectionForm.value,
        id: this.routerParams.id
      }
      const res: any = await this.services.updatePayInfo(params);
      if (res.code == 0) {
        this.message.success('操作成功');
        this.isCollectionVisible = false;
        this.loadDetailsData();
      } else {
        this.message.error(res.message);
      }
    } else {
      Object.values(this.collectionForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }

  /**
   * ----------------------------------------------------------------
   * 打款 Modal
   * ----------------------------------------------------------------
   */
  showPaymentModal() {
    this.paymentForm.reset();
    this.isPaymentVisible = true;
  }
  paymentCancel() {
    this.isPaymentVisible = false;
  }
  // 原因选择
  reasonChange(value: any) {
    let tmpObj = this.paymentReasons.find((item: any) => item.value == value);
    this.paymentForm.get('remarks')?.setValue(tmpObj.label);
  }
  async paymentOperation(num: number) {
    let params: any = {
      id: this.routerParams.id,
      ostat: num == 0 ? 18 : 19 // 18-打款失败  19-打款成功
    }
    if (num == 0) {
      // 打款失败
      if (this.paymentForm.valid) {
        let failParams = {
          ...params,
          ...this.paymentForm.value
        }
        await this.paymentInterface(failParams);
      } else {
        Object.values(this.paymentForm.controls).forEach(control => {
          if (control.invalid) {
            control.markAsDirty();
            control.updateValueAndValidity({ onlySelf: true });
          }
        });
      }
    } else {
      // 打款成功
      this.modal.warning({
        nzTitle: '提示',
        nzContent: '确定要将订单改为打款完成状态？',
        nzOnOk: () => {
          this.paymentInterface(params);
        },
      });
    }
  }
  async paymentInterface(params: any) {
    const res: any = await this.services.savePaymentData(params);
    if (res.code == 0) {
      this.message.success('操作成功');
      this.isPaymentVisible = false;
      this.loadDetailsData();
    } else {
      this.message.error(res.message);
    }
  }
  
  /**
   * ----------------------------------------------------------------
   * 不卖了/收钱 Modal
   * ----------------------------------------------------------------
   */
  machineOpera(num: number) {
    this.machineType = num;
    if (num == 0) {
      this.returnGoodsForm.reset();
      this.adressText = '';
      this.isReturnGoodsVisible = true;
    } else {
      this.machineForm.reset();
      this.isMachineVisible = true;
    }
  }
  machineCancel() {
    this.isMachineVisible = false;
    this.isReturnGoodsVisible = false;
  }
  // 立即收钱
  async submitMachine() {
    if (this.machineForm.valid) {
      let params = {
        ...this.machineForm.value,
        id: this.routerParams.id,
        ostat: 16 // 22：不卖了 16：立即收钱
      }
      const res: any = await this.services.saveBackOrSellData(params);
      if (res.code == 0) {
        this.message.success('操作成功');
        this.isMachineVisible = false;
        this.loadDetailsData();
      } else {
        this.message.error(res.message);
      }
    } else {
      Object.values(this.machineForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }
  // 不卖--退货
  async submitReturnGoods() {
    if (this.returnGoodsForm.valid) {
      let addressIdArrs = this.returnGoodsForm.get('backI5addrid')?.value || [];
      let params = {
        ...this.returnGoodsForm.value,
        id: this.routerParams.id,
        ostat: 22, // 22：不卖了 16：立即收钱
        backExparea: this.adressText,
        backI5addrid: this.returnGoodsForm.get('backI5addrid')?.value[addressIdArrs.length - 1] || '',
        isResultGoods: 0 // 是否有无法验机且退货机器 0否 1是 2表示已经退回
        // backI5addrid: this.returnGoodsForm.get('backI5addrid')?.value.join(',')
      }
      this.returnSubLoading = true;
      const res: any = await this.services.saveBackOrSellData(params);
      this.returnSubLoading = false;

      if (res.code == 0) {
        this.message.success('操作成功');
        this.isReturnGoodsVisible = false;
        this.loadDetailsData();
      } else {
        this.message.error(res.message);
      }
    } else {
      Object.values(this.returnGoodsForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }

  /**
   * ----------------------------------------------------------------
   * 添加退货信息 & 生成出库单 Modal
   * ----------------------------------------------------------------
   */
  setArea(districtId: any) {
    // 地区 设置默认值
    if (!districtId) {
      return
    }
    // this.returnInfosForm.get('backI5addrid')?.setValue([]);
    let arrs: any = [];
    // 省
    for (const key in this.addressArea.province) {
      let province = this.addressArea.province[key];
      // 市
      for (const k in this.addressArea.city[province.value]) {
        let city = this.addressArea.city[province.value][k];
        // 区
        for (let index = 0; index < this.addressArea.county[city.value].length; index++) {
          const county = this.addressArea.county[city.value][index];
          if (county.value == districtId) {
            // this.returnInfosForm.get('backI5addrid')?.setValue([province.value, city.value, county.value]);
            arrs = [province.value, city.value, county.value];
            break;
          }
        }
      }
    }
    return arrs;
  }
  showReturnInfoModal() {
    this.returnInfosForm.reset();

    // 默认取寄件信息
    this.returnInfosForm.patchValue({
      resultQuantity: this.orderDetailsData?.resultQuantity || '', // 退货数量
      isFreight: this.orderDetailsData?.isFreight || 0, // 邮费承担
      backLnker: this.orderDetailsData?.backLnker ? this.orderDetailsData?.backLnker : this.orderDetailsData?.lnker,
      backLnktel: this.orderDetailsData?.backLnktel ? this.orderDetailsData?.backLnktel : this.orderDetailsData?.lnktel,
      // backI5addrid: this.orderDetailsData?.addressIds ? this.orderDetailsData?.addressIds.split(',').map((item: any) => +item) : [],
      backExpdtl: this.orderDetailsData?.backExpdtl ? this.orderDetailsData?.backExpdtl : this.orderDetailsData?.expdtl
    })
    let tmpArr = this.setArea(this.orderDetailsData?.backI5addrid ? this.orderDetailsData?.backI5addrid : this.orderDetailsData?.exprgn);
    this.onChanges(tmpArr);
    this.returnInfosForm.get('backI5addrid')?.setValue(tmpArr);
    this.isReturnInfoVisible = true;
  }
  returnInfoCancel() {
    this.isReturnInfoVisible = false;
  }
  async submitReturnInfos() {
    if (this.returnInfosForm.valid) {
      let addressIdArrs = this.returnInfosForm.get('backI5addrid')?.value || [];
      let params = {
        id: this.routerParams.id, // 订单ID
        resultQuantity: this.returnInfosForm.get('resultQuantity')?.value, // 退货数量
        isFreight: this.returnInfosForm.get('isFreight')?.value, // 邮费承担
        backLnker: this.returnInfosForm.get('backLnker')?.value, // 退货用户名
        backLnktel: this.returnInfosForm.get('backLnktel')?.value, // 退货手机号
        backI5addrid: addressIdArrs[addressIdArrs.length - 1], // 退货地址ID
        backExpdtl: this.returnInfosForm.get('backExpdtl')?.value, // 退货详情地址
        backExparea: this.adressText || this.orderDetailsData.backExparea,
        addressIds: addressIdArrs.join(',') // 省市区
      }

      const res: any = await this.services.updateReturnInfoData(params);
      if (res.code == 0) {
        this.message.success('操作成功', { nzDuration: 5000 });
        this.isReturnInfoVisible = false;
        this.loadDetailsData();
      } else {
        this.message.error(res.message);
      }
    } else {
      Object.values(this.returnInfosForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }
  // 生成出库单
  async warehouseConfirm() {
    // let addressIdArrs = this.orderDetailsData?.addressIds.split(',') || [];
    let params = {
      backLnker: this.orderDetailsData.backLnker || '', // 退货用户名
      backLnktel: this.orderDetailsData.backLnktel || '', // 退货手机号
      backExpdtl: this.orderDetailsData.backExpdtl || '', // 用户退货详情街道地址
      backRemarks: this.orderDetailsData.backRemarks || '', // 退货备注

      id: this.routerParams.id,
      ostat: 22, // 22：不卖了 16：立即收钱
      backExparea: this.orderDetailsData.backExparea,
      backI5addrid: this.orderDetailsData.backI5addrid || '',
      isResultGoods: 1 // 是否有无法验机且退货机器 0否 1是 2表示已经退回
    }
    
    this.returnSubLoading = true;
    const res: any = await this.services.saveBackOrSellData(params);
    this.returnSubLoading = false;

    if (res.code == 0) {
      this.message.success('操作成功');
      setTimeout(() => {
        this.loadDetailsData();
      }, 1000)
    } else {
      this.message.error(res.message);
    }
  }

  /**
   * ----------------------------------------------------------------
   * 跟进 Modal
   * ----------------------------------------------------------------
   */
  showFollowModal() {
    this.followForm.reset();
    this.isFollowVisible = true;
  }
  followCancel() {
    this.isFollowVisible = false;
  }
  async submitFollow() {
    if (this.followForm.valid) {
      let params = {
        ...this.followForm.value,
        id: this.routerParams.id
      }
      const res: any = await this.services.orderFollowUpData(params);
      if (res.code == 0) {
        this.message.success('操作成功');
        this.isFollowVisible = false;
        this.loadDetailsData();
      } else {
        this.message.error(res.message);
      }
    } else {
      Object.values(this.followForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }

  /**
   * ----------------------------------------------------------------
   * 验机详情--添加信息 Modal
   * ----------------------------------------------------------------
   */
  showReasonModal(item: any) {
    this.reasonItem = item;
    this.reasonForm.reset();
    this.isReasonVisible = true;
  }
  async submitReason() {
    if (this.reasonForm.valid) {
      let params = {
        orderId: this.routerParams.id, // 订单ID，
        phoneCheckId: this.reasonItem.id, // 验机id
        ...this.reasonForm.value
      }
      // return
      const res: any = await this.services.addCheckInfoData(params);
      if (res.code == 0) {
        this.message.success('操作成功');
        this.isReasonVisible = false;
        this.loadDetailsData();
      } else {
        this.message.error(res.message);
      }
    } else {
      Object.values(this.reasonForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }

  /**
   * ----------------------------------------------------------------
   * 取消订单 Modal
   * ----------------------------------------------------------------
   */
  showOrderCancel() {
    this.isCancelVisible = true;
  }
  orderCancel() {
    this.cancelOrderForm.reset();
    this.isCancelVisible = false;
  }
  async submitCancelOrder() {
    if (this.cancelOrderForm.valid) {
      let params = {
        id: this.routerParams.id,
        ...this.cancelOrderForm.value
      }
      const res: any = await this.services.refundOrderData(params);
      if (res.code == 0) {
        this.message.success('取消订单成功');
        this.loadDetailsData();
        this.orderCancel();
      } else {
        this.message.error(res.message);
      }
    } else {
      Object.values(this.cancelOrderForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }

  /**
   * ----------------------------------------------------------------
   * 继续回收、反悔退货 Modal
   * ----------------------------------------------------------------
   */
  backOffShowModal(num: number) {
    this.adressText = '';
    if (num === 1) {
      this.isContinueVisible = true;
      this.continueOrderForm.reset();
    } else {
      // 返回退货
      this.regretOrderForm.reset();
      this.regretOrderForm.patchValue({
        resultQuantity: this.orderDetailsData?.resultQuantity || '', // 退货数量
        isFreight: this.orderDetailsData?.isFreight || 0, // 邮费承担 0我司 1用户
        backRemarks: this.orderDetailsData?.backRemarks || '', // 退货原因
        backLnker: this.orderDetailsData?.backLnker || '', // 收货人
        backLnktel: this.orderDetailsData?.backLnktel || '', // 手机号码
        // backI5addrid: ['', [Validators.required]], // 退货地址
        backExpdtl: this.orderDetailsData?.backExpdtl || '', // 详细地址
        note: '', // 备注
        backExparea: this.orderDetailsData?.backExparea || '' // 地址拼接
      })
      let tmpArr = this.setArea(this.orderDetailsData?.backI5addrid);
      this.regretOrderForm.get('backI5addrid')?.setValue(tmpArr);
      this.isRegretVisible = true;
    }
  }
  continueRegretCancel(type: number) {
    if (type === 0) {
      this.isContinueVisible = false;
    } else {
      this.isRegretVisible = false;
    }
  }
  // 反悔退货
  async refundOrderGoods() {
    if (this.regretOrderForm.valid) {
      let addArr = this.regretOrderForm.value.backI5addrid || [];
      let params  = {
        ...this.regretOrderForm.value,
        id: this.routerParams.id,
        backI5addrid: addArr.length ? addArr[addArr.length - 1] : '',
        backExparea: this.adressText || this.orderDetailsData?.backExparea // 地址拼接
      }
      
      const res: any = await this.services.refundOrderGoodsData(params);
      if (res.code === 0) {
        this.isRegretVisible = false;
        this.message.success('操作成功');
        this.loadDetailsData();
      } else {
        this.message.error(res.message);
      }
    } else {
      Object.values(this.regretOrderForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }
  // 继续回收
  async continueRecycling() {
    if (!this.continueOrderForm.value.remark) {
      this.message.warning('请输入备注');
      return
    }
    const res: any = await this.services.continueRecyclingData({id: this.routerParams.id, ...this.continueOrderForm.value});
    if (res.code === 0) {
      this.isContinueVisible = false;
      this.message.success('操作成功');
      this.loadDetailsData();
    } else {
      this.message.error(res.message);
    }
  }

  // 字符串查找
  isContain(str: string, substr: string){
    return new RegExp(substr).test(str);
  }
  // 订单来源filter
  filterPlatform(platform: number) {
    let tempObj = this.orderSourceOptions.find((item: any) => {
      return item.content == platform;
    })
    return tempObj ? tempObj.name : '-'
  }
  // 评估情况Str
  situationFilter(arry: any[]) {
    if (arry && arry.length) {
      
    }
  }

  /**
   * 跳转验机报告页面
   * @param type 0：新增，1：编辑，2：查看
   */
  jumpReport(type: number, item?: any) {
    let userInfo = JSON.parse((localStorage as any).getItem('userInfos')) || {};
    if (
      type == 1 &&
      this.orderDetailsData.checkName &&
      userInfo.realName != this.orderDetailsData.checkName
    ) {
      this.message.warning('您不是当前订单验机师，不可操作!');
      return
    }

    let routerParams: any = {
      ostat: this.orderDetailsData.ostat || '',
      type: type,
      okey: this.orderDetailsData.okey || '', // 订单号
      previewParams: JSON.stringify(this.previewParams), // 查看评估详情params
      recycleModel: JSON.stringify(this.orderRecycleModel), // 机型估价详情
      orderWay: this.orderDetailsData.orderWay,
      assessmentDetails: JSON.stringify({
        orderWay: this.orderDetailsData.orderWay,
        umname: this.orderDetailsData.umname,
        uprc: this.orderDetailsData.uprc, // 评估价
        aprc: this.orderDetailsData.aprc, // 加价
        cprc: this.orderDetailsData.cprc, // 回收下单抽奖
        ueval: JSON.parse(this.orderDetailsData.ueval) // 评估情况
      }) // 机器评估详情
    }

    if ([1, 2].includes(type)) {
      routerParams.id = item.id;
    }
    // return
    this.router.navigate(['/aisi-recyc/inspectedMachineEdit'],{
      queryParams: {...routerParams}
    })
  }

  // 查看评估详情
  assessPreview() {
    this.detailRef.getSubjectList();
    this.detailRef.isVisible = true;
  }
  
  // 验机详情合计
  machineReduce(arrs: any[]) {
    let sum = 0;
    if (arrs.length) {
      sum = arrs.reduce((total, item) => {
        return total + (item.price || 0)
      }, 0)
    }
    return sum;
  }

  // 查看验机报告
  showReportModal(item: any) {
    let params = {
      phoneCode: item.phoneCode // 机器编号
    }
    this.reportModalRef.loadData(params);
    this.reportModalRef.isVisible = true;
  }

  // 查看物流详情
  showLogisticsModal(list: Array<any>) {
    this.logisticsLists = list.length ? list.reverse() : [];
    this.isLogisticsVisible = true;
  }

  // 机器验机详情 回收文字提示
  returnTextFilter() {
    let isSystemReturn = false;
    if (this.machineDetailsTable.length) {
      isSystemReturn = this.machineDetailsTable.some((item: any) => item.status === 5);
    }

    return isSystemReturn ? '系统拒绝回收' : '用户拒绝回收';
  }

  /**
   * 加价设置 Modal
   * ----------------------------------------------------------------
   */
  showMakeupModal() {
    this.makeupVisible = true;
  }
  submitSetupCoupon(res: any) {
    console.log('makeup setup', res);
    this.loadDetailsData();
  }

  // 机器验机详情验机加价合计
  machineMakeupSum() {
    let sum = 0;
    if (this.machineDetailsTable.length) {
      sum = this.machineDetailsTable.reduce((total: number, item: any) => {
        return total + (item.aprc || 0);
      }, 0)
    }
    return sum;
  }

  /**
   * 关闭订单 Modal
   * ----------------------------------------------------------------
   */
  showcloseOrder() {
    this.closeOrderVisisble = true;
  }

  async subCloseOrder() {
    if (!this.closeOrderRemark) {
      this.message.warning('请输入关闭原因');
      return
    }
    let params = {
      id: this.orderDetailsData.id,
      note: this.closeOrderRemark
    }

    this.closeOrderLoading = true;
    const res: any = await this.services.closeOrderData(params);
    this.closeOrderLoading = false;

    if (res.code === 0) {
      this.closeOrderVisisble = false;
      this.message.success('订单已关闭');
      this.loadDetailsData();
    } else {
      this.message.error(res.message);
    }
  }

  /**
   * 商品信息 Modal
   * ----------------------------------------------------------------
   */
  // 商品信息合计
  totalReduceNum(key: string) {
    let tempNum = 0;
    if (this.goodsTableData.length) {
      tempNum = this.goodsTableData.reduce((total: any, item: any) => {
        return total + (item[key] || 0);
      }, 0);
    }
    return tempNum || 0;
  }

  // 商品信息退货量合计
  totalReturnNum(key: string) {
    let returnNum: any = [];
    returnNum = this.goodsTableData.filter((item: any) => item[key] > 0);
    
    return returnNum?.length || 0;
  }

  /**
   * 发送短信
   * ----------------------------------------------------------------
   */
  showSendMessageModal() {
    this.msgTemplType = null;
    this.msgTemplContent = '';
    this.isSendMsgVisible = true;
  }

  msgTempChange(val: any) {
    let tempObj: any = this.shortMsgOptions.find(el => el.id === val);
    this.msgTemplContent = tempObj?.value || '';
  }

  verifSendMsgData() {
    if (this.commonService.isEmpty(this.orderDetailsData.lnktel)) {
      this.message.warning('当前寄件信息联系电话为空');
      return false;
    } else if (this.commonService.isEmpty(this.msgTemplType)) {
      this.message.warning('请先选择短信模板');
      return false;
    } else {
      return true;
    }
  }

  async submitSendMsgData() {
    if (!this.verifSendMsgData()) {
      return
    }

    let params = {
      lnktel: this.orderDetailsData.lnktel,
      type: this.msgTemplType
    }
    this.sendMsgLoading = true;
    const {code, data, message}: any = await this.services.backSendMessageData(params);
    this.sendMsgLoading = false;
    
    if (code === 0) {
      this.message.success('操作成功');
      this.isSendMsgVisible = false;
    } else {
      this.message.error(message);
    }
  }

  // Copy
  copyText(str: any) {
    this.commonService.copyStr(str);
  }
}
